package com.dc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.ResponseResultVO;
import com.dc.entity.WorkOrder;
import com.dc.entity.ro.FireWorkOrderRO;
import com.dc.entity.ro.MaintenanceWorkOrderRO;
import com.dc.entity.ro.RepairWorkOrderRO;
import com.dc.mapper.DeviceMapper;
import com.dc.mapper.WorkOrderMapper;
import com.dc.model.Device;
import com.dc.service.MaintenanceWorkOrderService;
import com.dc.service.RepairWorkOrderService;
import com.dc.service.WorkOrderService;
import com.dc.util.RedisUtil;
import com.dc.util.SnowflakeIdWorker;
import com.dc.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder> implements WorkOrderService {

    @Resource
    private WorkOrderMapper workOrderMapper;
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private RepairWorkOrderService repairWorkOrderService;
    @Resource
    private MaintenanceWorkOrderService maintenanceWorkOrderService;

    /**
     * 查询
     *
     * @param ro
     * @return
     */
    @Override
    public ResponseResultVO selectWorkOrderList(FireWorkOrderRO ro) {
        Page page = new Page<Map<String, Object>>(ro.getCurrentPage(), ro.getPageSize());
        LambdaQueryWrapper<WorkOrder> queryWrapper = new LambdaQueryWrapper<WorkOrder>()
                .eq(null != ro.getType() && -1 != ro.getType(), WorkOrder::getType, ro.getType())
                // 特殊处理
                .in(-1 == ro.getType(), WorkOrder::getType, new String[]{"0", "1", "2", "5"})
                .orderByDesc(WorkOrder::getCreateTime);
        Page<WorkOrder> orderPage = workOrderMapper.selectPage(page, queryWrapper);
        for (WorkOrder record : orderPage.getRecords()) {
            // 查询对应的设备信息，编号是唯一的
            Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>()
                    .eq(Device::getSerialNumber, record.getSerialNumber()));
            if (device != null) {
                record.setDevice(device);
            }
        }
        orderPage.setTotal(workOrderMapper.selectCount(queryWrapper));
        return ResponseResultVO.resultList(orderPage, ro);
    }

    /**
     * 新增
     *
     * @param ro
     * @return
     */
    @Override
    @Transactional
    public ResponseResultVO insertWorkOrder(FireWorkOrderRO ro) {
        WorkOrder workOrder = new WorkOrder();
        BeanUtils.copyProperties(ro, workOrder);
        workOrder.setId(SnowflakeIdWorker.generateId());
        // 系统设备 发生故障 会有故障信息
        workOrder.setNumber(redisUtil.serialNumber("GZCZ"));
        workOrder.setUserId(Long.valueOf(UserUtil.getUserId()));
        workOrder.setUserName(String.valueOf(redisUtil.get(UserUtil.getUserId())));
        workOrder.setType(ro.getType());
        return ResponseResultVO.successResult(workOrderMapper.insert(workOrder));
    }

    @Override
    public ResponseResultVO selectTypeNumber() {

        Map<Integer, Long> collect = workOrderMapper.selectList(new LambdaQueryWrapper<WorkOrder>()).stream()
                .filter(cc -> cc.getType() != 4 && cc.getType() != 3)
                .collect(Collectors.groupingBy(WorkOrder::getType, Collectors.counting()));

        Map map = new HashMap<>();
        // 汇总
        map.put("all", collect.values().stream().collect(Collectors.summingLong(Long::longValue)));
        for (Integer integer : collect.keySet()) {
            if (integer == 0) {
                map.put("fault", collect.get(integer));
            }
            // 维保
            if (integer == 1) {
                map.put("maintenance", collect.get(integer));
            }
            // 报修
            if (integer == 2) {
                map.put("repairs", collect.get(integer));
            }
            if (integer == 5) {
                map.put("alarm", collect.get(integer));
            }
        }
        return ResponseResultVO.successResult(map);
    }

    /**
     * 修改
     *
     * @param ro
     * @return
     */
    @Override
    @Transactional
    public ResponseResultVO updateWorkOrder(FireWorkOrderRO ro) {
        WorkOrder workOrder = new WorkOrder();
        workOrder.setId(ro.getId());
        workOrder.setStatus(2);
        // 先根据工单编号完成故障
        int i = workOrderMapper.updateById(workOrder);
        if (i > 0) {
            ro.setId(null);
            ResponseResultVO responseResultVO = null;
            if (ro.getType() == 2) {
                RepairWorkOrderRO repairWorkOrder = new RepairWorkOrderRO();
                BeanUtils.copyProperties(ro, repairWorkOrder);
                responseResultVO = repairWorkOrderService.insertRepairWorkOrder(repairWorkOrder);
            }
            if (ro.getType() == 1) {
                MaintenanceWorkOrderRO maintenanceWorkOrderRO = new MaintenanceWorkOrderRO();
                BeanUtils.copyProperties(ro, maintenanceWorkOrderRO);
                responseResultVO = maintenanceWorkOrderService.insertMaintenanceWorkOrder(maintenanceWorkOrderRO);
            }
            return responseResultVO;
        }
        return ResponseResultVO.failResult("失败");
    }
}
